<template>
	<view>
		<view v-if="inPorcessOrder != null" class="order-process" @click="toOrder">您有进行中的订单,点击查看</view>

		<map id="map" :longitude="from.longitude" :latitude="from.latitude" :style="contentStyle" scale="15"
			:enable-traffic="false" :show-location="true" :enable-poi="true" class="map">
			<cover-image class="location" src="../../static/workbench/location.png"
				@tap="toLocationHandle()"></cover-image>
		</map>

		<view class="panel">
			<view class="from" @tap="chooseLocationHandle('from')">
				<text>{{ from.address }}</text>
			</view>
			<view class="dashed-line"></view>
			<view class="to" @tap="chooseLocationHandle('to')">
				<text>{{ to.address }}</text>
			</view>
			<button class="btn" @tap="toCreateOrderHandle">查看路线</button>
		</view>
	</view>
</template>

<script>
	import GtPush from '../../lib/gtpush-min.js'
	let QQMapWX = require('../../lib/qqmap-wx-jssdk.min.js');

	//地图点选插件
	const chooseLocation = requirePlugin('chooseLocation');
	let qqmapsdk;

	export default {
		data() {
			return {
				//窗口样式
				contentStyle: '',
				windowHeight: 0,
				//地图对象
				map: null,
				//开始位置
				from: {
					address: '输入你的开始位置',
					longitude: 0,
					latitude: 0
				},
				//结束位置
				to: {
					address: '输入你的目的地',
					longitude: 0,
					latitude: 0
				},
				//标记:开始位置点选或者结束位置点选
				chooseType: "",
				chooseFromOrToflag: null,
				inPorcessOrder: null,
				getui: {
					appid: '7i5yGYbYBG7q275zJ7Cqh5',
					cid: '',
					online: false,
					messages: '',
				},
			};
		},
		methods: {
			//初始化
			init() {
				const _this = this;
				qqmapsdk = new QQMapWX({
					key: _this.Constants.QQMAP_KEY // 必填
				});
				//处理窗口样式
				let windowHeight = uni.getSystemInfoSync().windowHeight;
				_this.windowHeight = windowHeight - 200;
				_this.contentStyle = `height:${_this.windowHeight}px;`;
			},
			//初始化地图
			initMap() {
				const _this = this;
				_this._mapContext = uni.createMapContext("map", _this);
				//@TODO 测试数据
				if (uni.getStorageSync("from")) {
					_this.from.longitude = uni.getStorageSync("from").longitude;
					_this.from.latitude = uni.getStorageSync("from").latitude;
					_this.chooseFromOrToflag = true
				} else {
					uni.getLocation({
						type: 'wgs84', // 返回可以用于uni.openLocation的经纬度，默认为wgs84的gps坐标
						success: (res) => {
							_this.from.longitude = res.longitude;
							_this.from.latitude = res.latitude;
						},
						fail: (err) => {
							console.error('获取位置失败：', err);
						}
					});
				}
				//@TODO 测试数据
				if (uni.getStorageSync("to")) {
					_this.to.longitude = uni.getStorageSync("to").longitude;
					_this.to.latitude = uni.getStorageSync("to").latitude;
					_this.to.address = uni.getStorageSync("to").address;
					_this.chooseFromOrToflag = true
				}
			},
			//通过腾讯地图接口位置信息
			reverseGeocoder() {
				const _this = this;
				//@TODO 测试数据
				if (uni.getStorageSync("from")) {
					_this.from.address = uni.getStorageSync("from").address;
				} else {
					qqmapsdk.reverseGeocoder({
						success: (res) => {
							_this.from.address = res.result.formatted_addresses.standard_address;
							uni.setStorageSync("from", _this.from);
						},
						fail: function(error) {
							uni.showToast({
								title: '获取地址失败',
								icon: 'error'
							})
						}
					})
				}
			},
			//初始化个推
			initGeTui() {
				const _this = this;
				GtPush.setDebugMode(true)
				GtPush.init({
					appid: _this.getui.appid,
					onClientId: (res) => {
						_this.getui.cid = res.cid
						_this.get("/message/app/gtPush/bindAlias/" + _this.getui.cid, (res) => {
							if (res.success) {
								console.log("---初始化个推成功---")
							} else {
								uni.showToast({
									title: res.message,
									icon: "error"
								})
								return;
							}
						})
					},
					onlineState: (res) => {
						_this.getui.online = res.online
					},
					onPushMsg: (res) => {
						console.log("---收到个推消息---")
						let messageObj = JSON.parse(res.message);
						// 提取信息
						const orderNo = messageObj.orderNo; // 订单号
						const type = messageObj.type; // 订单号
						if (type == 0 && orderNo == uni.getStorageSync("orderNo")) {
							//乘客取消订单--重新获取当前司机工作状态
							console.log("---司机取消订单---")
							uni.showToast({
								title: "司机取消订单",
								icon: "error",
							})
							uni.$emit('closeMove');
							_this.getCustomerOrderStatus();
						}
					},
					onError: (res) => {
						_this.getui.messages += "onError: " + res.error + "\n"
					}
				})
			},
			//重定位到当前位置
			toLocationHandle() {
				let _this = this;
				_this._mapContext.moveToLocation();
			},
			//腾讯地图选点
			chooseLocationHandle(type) {
				//当前选点是起点还是终点
				this.chooseType = type;
				//腾讯地图选点服务
				const key = this.Constants.QQMAP_KEY; //使用在腾讯位置服务申请的key
				const referer = 'swiftride'; //调用插件的app的名称
				const category = '生活服务,娱乐休闲';
				wx.navigateTo({
					url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer + '&category=' +
						category
				});
			},
			//获取位置信息
			getLocation(location) {
				const _this = this;
				if (location) {
					_this.chooseFromOrToflag = true;
					console.log("---初始化位置成功---")
					if (_this.chooseType == "from") {
						_this.from.address = location.address;
						_this.from.latitude = location.latitude;
						_this.from.longitude = location.longitude;
						uni.setStorageSync("from", _this.from);
					} else if (_this.chooseType == "to") {
						_this.to.address = location.address;
						_this.to.latitude = location.latitude;
						_this.to.longitude = location.longitude;
						uni.setStorageSync("to", _this.to);
					}
				}
			},
			//跳转到查看路线页面
			toCreateOrderHandle() {
				if (this.chooseFromOrToflag) {
					uni.navigateTo({
						url: "/pages/create_order/create_order"
					})
				} else {
					uni.showToast({
						title: "请输入目的地",
						icon: "error"
					})
				}
			},
			//查询最后一次接单状态
			getCustomerOrderStatus(callback) {
				const _this = this;
				_this.get("/order/app/order/customer/lastOrder", (res) => {
					let {
						success,
						message,
						data
					} = res;
					if (success && data) {
						console.log("---获取最近一次订单成功---")
						if (data.status == _this.Constants.OrderStatus.ORDER_STATUS_WAIT ||
							data.status == _this.Constants.OrderStatus.ORDER_STATUS_ACCEPTED ||
							data.status == _this.Constants.OrderStatus.ORDER_STATUS_ARRIVE ||
							data.status == _this.Constants.OrderStatus.ORDER_STATUS_START_DRIVING ||
							data.status == _this.Constants.OrderStatus.ORDER_STATUS_COMPLETE_DRIVED ||
							data.status == _this.Constants.OrderStatus.ORDER_STATUS_ENSURE ||
							data.status == _this.Constants.OrderStatus.ORDER_STATUS_NOT_PAY) {
							_this.inPorcessOrder = data;
						} else {
							_this.inPorcessOrder = null;
						}
					}
					if (typeof callback === 'function') {
						callback(); // 数据更新后执行回调
					}
				});
			},
			//根据订单状态跳转页面
			toOrder() {
				console.log("------------执行toOrder----------------");
				const _this = this;
				_this.getCustomerOrderStatus(function() {
					if (_this.inPorcessOrder) {
						_this.processOrder();
					}
				});
			},
			// 根据订单状态跳转页面--处理逻辑
			processOrder() {
				const _this = this;
				if (_this.inPorcessOrder.status == _this.Constants.OrderStatus.ORDER_STATUS_WAIT) {
					uni.navigateTo({
						url: "/pages/create_order/create_order?orderNo=" + _this.inPorcessOrder.orderNo
					})
				} else if (_this.inPorcessOrder.status == _this.Constants.OrderStatus.ORDER_STATUS_ACCEPTED ||
					_this.inPorcessOrder.status == _this.Constants.OrderStatus.ORDER_STATUS_ARRIVE ||
					_this.inPorcessOrder.status == _this.Constants.OrderStatus.ORDER_STATUS_START_DRIVING) {
					uni.navigateTo({
						url: "/pages/move/move?orderNo=" + _this.inPorcessOrder.orderNo
					})
				} else if (_this.inPorcessOrder.status == _this.Constants.OrderStatus.ORDER_STATUS_COMPLETE_DRIVED ||
					_this.inPorcessOrder.status == _this.Constants.OrderStatus.ORDER_STATUS_ENSURE ||
					_this.inPorcessOrder.status == _this.Constants.OrderStatus.ORDER_STATUS_NOT_PAY) {
					uni.navigateTo({
						url: "/pages/order/order?orderNo=" + _this.inPorcessOrder.orderNo
					})
				} else {
					//查询接单状态
					_this.getCustomerOrderStatus();
				}
			}
		},
		onLoad: function() {
			const _this = this;
			//初始化
			_this.init();
			//初始化地图
			_this.initMap();
			//通过腾讯地图接口位置信息
			_this.reverseGeocoder();
			//初始化个推
			_this.initGeTui();
		},
		onShow() {
			const _this = this;
			// 从地图选点插件返回后，在页面的onShow生命周期函数中能够调用插件接口，取得选点结果对象
			const location = chooseLocation.getLocation(); // 如果点击确认选点按钮，则返回选点结果对象，否则返回null
			//获取位置信息
			_this.getLocation(location);
			//查询接单状态
			_this.getCustomerOrderStatus();
		},
		onUnload() {
			// 页面卸载时设置插件选点数据为null，防止再次进入页面，geLocation返回的是上次选点结果
			chooseLocation.setLocation(null);
		}
	};
</script>

<style lang="less">
	@import url('workbench.less');
</style>